package com.ylx;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.util.DocumentUtil;
import org.apache.http.util.TextUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MySQLCamelCaseAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {

        final Editor mEditor = e.getData(PlatformDataKeys.EDITOR);

        if (null == mEditor) {
            return;
        }
        SelectionModel model = mEditor.getSelectionModel();
        final String selectedText = model.getSelectedText();
        if (TextUtils.isEmpty(selectedText)) {
            return;
        }
        DocumentUtil.writeInRunUndoTransparentAction(() -> {
            String toCamelCase = toSqlCamelCase(selectedText);
            int selectionStart = mEditor.getSelectionModel().getSelectionStart();
            int selectionEnd = mEditor.getSelectionModel().getSelectionEnd();
            mEditor.getDocument().replaceString(selectionStart, selectionEnd,toCamelCase);
        });
    }

    public static String toSqlCamelCase(String str){

        if (str.indexOf("_") == -1) {
            return str;
        }
        Pattern pattern = Pattern.compile("(FROM|from)");
        if (pattern.matcher(str).find()) {
            Pattern selectSqlPattern = Pattern.compile("(SELECT|select)?[\\s_\\S]*(FROM|from)");
            Matcher selectSqlMatcher = selectSqlPattern.matcher(str);
            if (selectSqlMatcher.find()) {

                String selectSql = selectSqlMatcher.group();

                String selectSql2 = selectSqlMatcher.group();

                Pattern linePattern = Pattern.compile("[a-zA-z]*_[a-zA-z]*");
                Matcher matcher = linePattern.matcher(selectSql);
                while (matcher.find()) {
                    String group = matcher.group();
                    String s = group +" as " + StringUtils.toCamelCase(group);
                    selectSql2 = selectSql2.replace(group,s);
                }
                return str.replace(selectSql,selectSql2);
            }
        }else {
            Pattern linePattern = Pattern.compile("[a-zA-z]*_[a-zA-z]*");
            Matcher matcher = linePattern.matcher(str);
            while (matcher.find()) {
                String group = matcher.group();
                String s = group +" as " + StringUtils.toCamelCase(group);
                str = str.replace(group,s);
            }
            return str;
        }

        return null;
    }
}
